<?php
namespace app\app\util;
use think\cache\driver\Redis;
use think\Request;

// 登陆用户id前缀
define('SID_PREFIX', 'tof:online:sid:');
// 登陆信息过期时间
define('OVERDATETIME', 15*24*60*60);
// redis处理用户登陆类的hash
define('ID_TOKEN','tof:id:token');


class OnlineUtils{

    // 用户名密码登陆
    public static function login($sid='',$user=[]){
        $redis = new Redis(['host'=>config('REDIS_HOST'),'password'=>config('REDIS_AUTH')]);
        $redis->set(SID_PREFIX.$sid,$user,OVERDATETIME);
        return true;
    }


    // sid登陆
    public static function sidLogin($sid='',$user=[]){
        $request = Request::instance();
        $header = $request->header();
        $sid = $sid=='' ? $header['token'] : $sid;
        $redis = new Redis(['host'=>config('REDIS_HOST'),'password'=>config('REDIS_AUTH')]);
        if($redis->set(SID_PREFIX.$sid,$user,OVERDATETIME)){
            return true;
        }else{
            return false;
        }
    }

    // 根据sid得到用户信息
    public static function getUserInfoBySid($sid=''){
        $request = Request::instance();
        $header = $request->header();
        $sid = $sid=='' ? $header['token'] : $sid;
        $redis = new Redis(['host'=>config('REDIS_HOST'),'password'=>config('REDIS_AUTH')]);
        if($redis->has(SID_PREFIX.$sid)){
            $user = $redis->get(SID_PREFIX.$sid);
            return $user;
        }else{
            return false;
        }
    }


    // 根据sid得到用户id
    public static function getUserIdBySid($sid=''){
        $request = Request::instance();
        $header = $request->header();
        $sid = $sid=='' ? $header['token'] : $sid;
        $redis = new Redis(['host'=>config('REDIS_HOST'),'password'=>config('REDIS_AUTH')]);
        if($redis->has(SID_PREFIX.$sid)){
            $user = $redis->get(SID_PREFIX.$sid);
            return $user['id'];
        }else{
            return false;
        }
    }


    // 请求是否登陆
    public static function requestIsLogin(){
        $request = Request::instance();
        $header = $request->header();  
        $sid = $header['token'] ? $header['token'] : '';
        $redis = new Redis(['host'=>config('REDIS_HOST'),'password'=>config('REDIS_AUTH')]);
        if($redis->has(SID_PREFIX.$sid)){
            return true;
        }else{
            return false;
        }
    }
    //登录过期
    public static function OutTime(){
        $request = Request::instance();
        $header = $request->header();  
        $sid = $header['token'] ? $header['token'] : '';
        $redis = new Redis(['host'=>config('REDIS_HOST'),'password'=>config('REDIS_AUTH')]);
        if($redis->expire(SID_PREFIX.$sid,0)){
            return true;
        }else{
            return false;
        }       
    }

}
